console.log("Start connecting neo4j.");
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase({
  url: 'http://104.209.33.91:7474',
  auth: {username: 'neo4j', password: 'GN_17'}
});
console.log("Neo4j connected.");
exports.neo4j = db;
exports.getUser = function (username, callback){
    db.cypher({
            query : 'MATCH (u:User) WHERE u.username = {username} RETURN u',
            params : {username : username}
        }, callback)
}
exports.createUser = async function(username, password, callback){
  try{
    let res = await new Promise((resolve, reject)=>{
        exports.getUser(username, function(err, res){
            if(err) reject(err)
            else resolve(res)
          })
      })
    if(res.length > 0) {
      callback({error: 'Username has been registered'})
      return;
    }
    res = await new Promise((resolve, reject)=>{
        db.cypher({
            query : 'CREATE (u:User {username: {username}, password : {password}}) RETURN u',
            params : {username : username, password : password}
          }, function(err, res){
            if(err) reject(err)
            resolve(res)
          })
      })
    callback(null, res[0]['u']['_id'])
  }catch(err){
    console.log(err)
  }
}

// exports.createUser('fakeuser2', '123456', (err, res)=>{
//   if(err) console.log(err)
//   else console.log(res)
// })
// exports.getUser('fakeuser',(err, res)=>{
//   if(err) console.log(err)
//   else console.log(res)
// })